/*
 * MunicipiosBusquedaFrame.java
 *
 * Created on 27 de abril de 2008, 02:37 PM
 */
package org.contabilidad.municipios;

import org.mybeans.Sesion;
import org.mybeans.MunicipiosBeans;
 
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author  avbravo
 */
public class MunicipiosBusquedaFrame extends javax.swing.JFrame {

    Sesion sesion;
    int fila = -1;
    DefaultTableModel modelo;
    MunicipiosBeans municipiosBeans;

    /** Creates new form MunicipiosBusquedaFrame */
    public MunicipiosBusquedaFrame() {
        initComponents();
         /*
             * Fondo
             */

            
              
             

             
             

            /*
             * fin del fondo
             */
        sesion = new Sesion();
        municipiosBeans = new MunicipiosBeans();
            String sql = "select * from municipies where idprovincia ='"+ sesion.getIdprovincia() +"' order by municipio";
    CargarTodosRegistros(sql);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldMunicipio = new javax.swing.JTextField();
        jButtonBuscar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButtonVerTodos = new javax.swing.JButton();
        jTextFieldIdMunicipio = new javax.swing.JTextField();
        jButtonBuscarCodigo = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldNuevoNombre = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Busqueda de Municipios");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Municipos");

        jTextFieldMunicipio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldMunicipioActionPerformed(evt);
            }
        });

        jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/consultar.png"))); // NOI18N
        jButtonBuscar.setToolTipText("Consultar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jLabel1.setText("Codigo");

        jButtonVerTodos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/view.png"))); // NOI18N
        jButtonVerTodos.setToolTipText("Ver Todos");
        jButtonVerTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerTodosActionPerformed(evt);
            }
        });

        jTextFieldIdMunicipio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdMunicipioActionPerformed(evt);
            }
        });

        jButtonBuscarCodigo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/consultar.png"))); // NOI18N
        jButtonBuscarCodigo.setToolTipText("Consultar");
        jButtonBuscarCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarCodigoActionPerformed(evt);
            }
        });

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Grupo"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel3.setText("Nuevo Nombre");

        jTextFieldNuevoNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldNuevoNombreActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButton1.setToolTipText("Actualizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(1, 1, 1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextFieldIdMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonBuscarCodigo))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextFieldMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonBuscar)))
                .addContainerGap(181, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
                .addGap(113, 113, 113))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(124, 124, 124)
                .addComponent(jButtonVerTodos, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(403, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldNuevoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(194, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldIdMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButtonBuscarCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldNuevoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonVerTodos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonRegresar, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                .addGap(12, 12, 12)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
 
    BuscarMunicipio();
    
}//GEN-LAST:event_jButtonBuscarActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed
 
    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonVerTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerTodosActionPerformed
 
    BuscarTodos();
}//GEN-LAST:event_jButtonVerTodosActionPerformed

private void jButtonBuscarCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarCodigoActionPerformed
 
BuscarCodigo();
}//GEN-LAST:event_jButtonBuscarCodigoActionPerformed

private void jTextFieldMunicipioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldMunicipioActionPerformed
 
    BuscarMunicipio();
}//GEN-LAST:event_jTextFieldMunicipioActionPerformed

private void jTextFieldIdMunicipioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIdMunicipioActionPerformed
 
    BuscarCodigo();
}//GEN-LAST:event_jTextFieldIdMunicipioActionPerformed

private void jTextFieldNuevoNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNuevoNombreActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jTextFieldNuevoNombreActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
     try {
         String idmunicipio= jTextFieldIdMunicipio.getText();
if (idmunicipio.equals("") || idmunicipio == null){
     JOptionPane.showMessageDialog(this, "Ingrese el nombre del municipio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
     return;
}
String municipionuevo= jTextFieldNuevoNombre.getText();
if (municipionuevo.equals("") || municipionuevo == null){
     JOptionPane.showMessageDialog(this, "Ingrese el nombre del municipio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
     return;
}

        String sql = "update municipies set municipio = ? where idmunicipio =?";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setString(1, municipionuevo);
        prest.setString(2,idmunicipio);


        int count = prest.executeUpdate();
        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Municipio actualizado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        jTextFieldMunicipio.setText(municipionuevo);
       BuscarTodos();


    } catch (Exception ex) {
        System.out.println("Error" + ex);
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MunicipiosBusquedaFrame().setVisible(true);
            }
        });
    }


    private void BuscarTodos(){
        String sql = "select * from municipies where idprovincia ='"+ sesion.getIdprovincia() +"' order by municipio";
    CargarTodosRegistros(sql);
    }
    private void BuscarMunicipio(){
        try {


        String municipio = (String) this.jTextFieldMunicipio.getText();
        String sql = "select * from municipies  where municipies.municipio like '%" + municipio + "%' and idprovincia ='" + sesion.getIdprovincia() + "' order by municipio";
        CargarTodosRegistros(sql);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    }
    
    private void BuscarCodigo(){
            try {


        String idmunicipio = (String) this.jTextFieldIdMunicipio.getText();
        String sql = "select * from municipies  where municipies.idmunicipio like '%" + idmunicipio + "%' and idprovincia ='"+ sesion.getIdprovincia() +"' order by municipio";
        CargarTodosRegistros(sql);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    }
    private void CargarTodosRegistros(String sql) {
        try {

            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            PreparedStatement psquery = sesion.con.prepareStatement(sql);
            ResultSet rs = psquery.executeQuery();

            modelo = new DefaultTableModel();
            // Creamos las columnas.
            modelo.addColumn("codigo");
            modelo.addColumn("municipio");
            modelo.addColumn("provincia");


// Bucle para cada resultado en la consulta
            while (rs.next()) {
                // Se crea un array que será una de las filas de la tabla.
                Object[] fila = new Object[3]; // Hay tres columnas en la tabla

                fila[0] = rs.getString("idmunicipio");
                fila[1] = rs.getString("municipio");
                fila[2] = rs.getString("idprovincia");
                modelo.addRow(fila);

            }
            this.jTable1.setModel(modelo);
            jTable1.setVisible(true);
            //aris++
            this.jTable1.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {

                    fila = jTable1.rowAtPoint(e.getPoint());
                    int columna = jTable1.columnAtPoint(e.getPoint());
                    if ((fila > -1) && (columna > -1)) {
                        jTextFieldIdMunicipio.setText(String.valueOf(jTable1.getValueAt(fila, 0)));
                        jTextFieldMunicipio.setText(String.valueOf(jTable1.getValueAt(fila, 1)));
                        jTextFieldNuevoNombre.setText(String.valueOf(jTable1.getValueAt(fila, 1)));
                        String IdProvincia = String.valueOf(jTable1.getValueAt(fila, 2));
                        municipiosBeans.setIdMunicipo((String) jTextFieldIdMunicipio.getText());
                        municipiosBeans.setMunicipio((String) jTextFieldMunicipio.getText());
                        municipiosBeans.setIdProvincia(IdProvincia);

                    }
                }
            });

            TableColumn column = jTable1.getColumnModel().getColumn(1);
            column.setPreferredWidth(200);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonBuscarCodigo;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JButton jButtonVerTodos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldIdMunicipio;
    private javax.swing.JTextField jTextFieldMunicipio;
    private javax.swing.JTextField jTextFieldNuevoNombre;
    // End of variables declaration//GEN-END:variables
}
